package com.guguskins.back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guguskins.back.common.exception.GlobalException;
import com.guguskins.back.entity.GuRole;
import com.guguskins.back.entity.GuRolePermission;
import com.guguskins.back.mapper.GuRoleMapper;
import com.guguskins.back.service.GuRolePermissionService;
import com.guguskins.back.service.GuRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guguskins.back.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-07-16
 */
@Service
public class GuRoleServiceImpl extends ServiceImpl<GuRoleMapper, GuRole> implements GuRoleService {
    @Autowired
    private GuRoleMapper roleMapper;

    @Autowired
    private GuRolePermissionService rolePermissionService;
    @Override
    public int add(GuRole role) {
        CommonUtil.checkParams(role.getRoleName());

        Integer count = roleMapper.selectCount(new QueryWrapper<GuRole>() {
            {
                eq("role_name", role.getRoleName());
            }
        });
        if (count > 0) {
            throw new GlobalException("用户组名已存在！");
        }

        int result = roleMapper.insert(role);

        if (!CollectionUtils.isEmpty(role.getPermissionIds())) {
            List<GuRolePermission> rolePermissionEntities = role.getPermissionIds().stream().map(permissionId -> {
                GuRolePermission rolePermissionEntity = new GuRolePermission();
                rolePermissionEntity.setRoleId(role.getId());
                rolePermissionEntity.setPermissionId(permissionId);
                return rolePermissionEntity;
            }).collect(Collectors.toList());
            rolePermissionService.saveBatch(rolePermissionEntities);
        }

        return result;
    }

    @Override
    public int edit(GuRole role) {
        CommonUtil.checkParams(role.getId());
        Integer count = roleMapper.selectCount(new QueryWrapper<GuRole>() {
            {
                eq("role_name", role.getRoleName());
                ne("id", role.getId());
            }
        });
        if (count > 0) {
            throw new GlobalException("用户组名已存在！");
        }
        int result = roleMapper.updateById(role);

        //todo 角色权限修改
        if (!CollectionUtils.isEmpty(role.getPermissionIds())) {
            List<Integer> permissionIds = rolePermissionService.listObjs(new QueryWrapper<GuRolePermission>() {
                {
                    select("permission_id");
                    eq("role_id", role.getId());
                }
            }, permissionId -> Integer.parseInt(permissionId.toString()));

//            if (!CollectionUtils.isEmpty(permissionIds)) {
            List<Integer> deleteList = permissionIds.stream().filter(permissionId -> !role.getPermissionIds().contains(permissionId)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deleteList)) {
                boolean remove = rolePermissionService.remove(new QueryWrapper<GuRolePermission>() {
                    {
                        eq("role_id", role.getId());
                        in("permission_id", deleteList);
                    }
                });

            }
            List<Integer> insertList = role.getPermissionIds().stream().filter(permissionId -> !permissionIds.contains(permissionId)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(insertList)) {
                List<GuRolePermission> insertPermissionList = insertList.stream().map(permissionId -> {
                    GuRolePermission rolePermissionEntity = new GuRolePermission();
                    rolePermissionEntity.setRoleId(role.getId());
                    rolePermissionEntity.setPermissionId(permissionId);
                    return rolePermissionEntity;
                }).collect(Collectors.toList());
                boolean saveBatch = rolePermissionService.saveBatch(insertPermissionList);

            }
//            }

        }
        return result;
    }

    @Override
    public int updateStatus(int[] ids, int status) {
        List<GuRole> roles = roleMapper.selectBatchIds(Collections.singletonList(ids));
        AtomicInteger count = new AtomicInteger();
        roles.forEach(role -> {
            role.setStatus(status);
            int result = roleMapper.updateById(role);
            count.addAndGet(result);

        });
        return count.get();
    }
}
